import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)

// 重写replace和push
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, okCallback, errCallback) {
    if (okCallback === undefined && errCallback === undefined) {
        originPush.call(this, location).catch(() => { })
    } else {
        originPush.call(this, location, okCallback, errCallback)
    }
}
VueRouter.prototype.replace = function (location, okCallback, errCallback) {
    if (okCallback === undefined && errCallback === undefined) {
        originReplace.call(this, location).catch(() => { })
    } else {
        originReplace.call(this, location, okCallback, errCallback)
    }
}


const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        // to和 from为路由对象，to表示到达，from表示来处
        // console.log(to, from);
        if (savedPosition) {
            return savedPosition
        } else {
            // return 期望滚动到哪个的位置
            return { x: 0, y: 0 }
        }
    }
})

// 白名单
const whiteList = [
    "home",
    "login",
    "register",
    "search",
    "detail",
    "addCart",
]
router.beforeEach((to, from, next) => {
    if (whiteList.includes(to.name) || store.state.passport.token) {
        next()
        return
    }
    next({
        name: 'login',
        query: {
            redirect: to.path
        }
    })
})


export default router



